package service

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
	"push/config/table"
	"strconv"
	"sync"

	//"push/config/table"
	"push/pool"
	"time"
)
//var RedisPoolConn redis.Conn
func StartCustomQueue(){
	//开始定时任务
	crontabStart()
	//初始化进程池
	//c := pool.InitRedisPool()
	//RedisPoolConn = pool.GetRedisPoolConn(c)

}
//获取队列信息
func getQueueData(c *redis.Pool) int{
	//c := pool.InitRedisPool()
	RedisPoolConn := pool.GetRedisPoolConn(c)
	v := pool.RedisLLen(RedisPoolConn,table.Redis_table_hongbao_list)
	pool.RedisConnClose(RedisPoolConn)
	return v
}
//定时任务开始
func crontabStart(){
	c := pool.InitRedisPool()
	var ch chan int
	ticker := time.NewTicker(time.Second * 1)
	go func() {
		for range ticker.C {
			fmt.Println()
			if(getQueueData(c) > 0){
				fmt.Println(time.Now().Format("2006-01-02 15:04:05"),"-->任务开始")
				gohandle(c)
			}else{
				fmt.Println(time.Now().Format("2006-01-02 15:04:05"),"-->没有任务可做")
			}
		}
		ch <- 1
	}()
	<-ch
}
func gohandle(c *redis.Pool) {
	var wg sync.WaitGroup
	for i := 0; i < 200; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			handlePushQueue(c)
		}()
	}
	wg.Wait()
}

func handlePushQueue(c *redis.Pool){
	RedisPoolConn := pool.GetRedisPoolConn(c)
	lockRedis(RedisPoolConn)
	pool.RedisConnClose(RedisPoolConn)
	//fmt.Println(c.ActiveCount(),c.Stats(),c.IdleCount())
}

func lockRedis(c redis.Conn) bool{
	queue_value ,err := redis.String(c.Do("LPOP", table.Redis_table_hongbao_list))
	if(queue_value ==""){return false}
	queue_table := fmt.Sprintf("%s%s", lockKey,queue_value)
	lockSuccess, err := c.Do("SETNX",queue_table,expire)
	if(err != nil || lockSuccess == int64(0) ){
		c.Do("LPUSH", table.Redis_table_hongbao_list,queue_value)
		ntime ,err := redis.String(c.Do("GET",queue_table))
		if(err != nil){fmt.Println(err)}
		t, err := strconv.ParseInt(ntime, 10, 64)
		if(t < time.Now().Unix()){
			fmt.Println( fmt.Sprintf("%s%s过期", lockKey,queue_value) )
			unlock(c,queue_value)
		}
		return false
	}
	unlockRedis(c,queue_value)
	sendhongbao(queue_value)
	return true
}
func sendhongbao (value string){
	fmt.Println(fmt.Sprintf("开始发放红包%s", value))
}

func unlockRedis(c redis.Conn,value string) bool{
	if _, err := c.Do("DEL", fmt.Sprintf("%s%s", lockKey,value)); err != nil {
		fmt.Println( fmt.Sprintf("%s%s解锁失败", lockKey,value) )
		return false
	}
	//fmt.Println( fmt.Sprintf("%s%s解锁成功", lockKey,value) )
	return true
}